package example.上下左右;

/**
 * 给一个01矩阵，1代表是陆地，0代表海洋，
 * 如果两个1相邻，那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
 * 岛屿: 相邻陆地可以组成一个岛屿（相邻:上下左右） 判断岛屿个数。
 */
// NC109 岛屿数量
public class Demo3 {

    // {'1','1','0','0','0'},
    // {'0','1','0','1','1'},
    // {'0','0','0','1','1'},
    // {'0','0','0','0','0'},
    // {'0','0','1','1','1'}    3
    public int solve(char[][] grid) {
        if (grid == null || grid.length == 0)
            return 0;
        if (grid.length == 1 && grid[0].length == 1) {
            return grid[0][0] == '1' ? 1 : 0;
        }
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }

    public void dfs(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0') {
            return;
        }
        grid[i][j] = '0';
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }
}
